package com.example.autopia.view.Adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.autopia.databinding.ViewholderTransactionActiveBinding
import com.example.autopia.databinding.ViewholderTransactionPastBinding
import com.example.autopia.model.Item.Transaction
import com.example.autopia.utilities.TimeManager
import com.example.autopia.view.Listeners.TransactionListener
import com.example.autopia.view.ViewHolders.Transactions.ActiveTransactionViewHolder
import com.example.autopia.view.ViewHolders.Transactions.PastTransactionViewHolder

class TransactionAdapter  :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private var oldList = emptyList<Transaction>().toMutableList()
    private lateinit var listener : TransactionListener
    private val timeManager = TimeManager()

     fun attachListener(listener: TransactionListener) {
        this.listener = listener
    }



    companion object {
        const val ACTIVE_VIEW = 0
        const val PAST_VIEW = 1
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return when (viewType) {
            ACTIVE_VIEW -> ActiveTransactionViewHolder(
                ViewholderTransactionActiveBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                ), inflater,timeManager
            )

            PAST_VIEW -> PastTransactionViewHolder(
                ViewholderTransactionPastBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                ), inflater,timeManager
            )

            else -> throw IllegalArgumentException("invalid item type")
        }
    }

    override fun getItemCount(): Int {
        return oldList.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        return when (holder.itemViewType) {
            ACTIVE_VIEW -> (holder as ActiveTransactionViewHolder).bind(
                oldList[position],listener
            )

            PAST_VIEW -> (holder as PastTransactionViewHolder).bind(
                oldList[position],
            )

            else -> throw IllegalArgumentException("invalid item type")
        }
    }

    override fun getItemViewType(position: Int): Int {
        return if (oldList[position].active) {
            ACTIVE_VIEW
        } else {
            PAST_VIEW
        }
    }

    fun setData(newPostList: List<Transaction>) {
        oldList = newPostList.toMutableList()
        notifyDataSetChanged()
    }
}